package com.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class TaskTrackerApp extends JFrame {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/task_tracker";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "zjq2020420520" +
            "";

    private JList<Task> taskList;
    private DefaultListModel<Task> listModel;
    private JTextField titleField, descriptionField;
    private JComboBox<String> priorityComboBox;
    private JButton addButton, updateButton, deleteButton;

    public TaskTrackerApp() {
        initializeUI();
        connectToDatabase();
        loadTasks();
    }

    private void initializeUI() {
        setTitle("任务追踪系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new BorderLayout());

        // 左侧任务列表
        listModel = new DefaultListModel<>();
        taskList = new JList<>(listModel);
        taskList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        taskList.setCellRenderer(new TaskListRenderer());
        JScrollPane listScrollPane = new JScrollPane(taskList);
        mainPanel.add(listScrollPane, BorderLayout.CENTER);

        // 右侧控制面板
        JPanel controlPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        gbc.gridx = 0;
        gbc.gridy = 0;
        controlPanel.add(new JLabel("标题:"), gbc);

        gbc.gridx = 1;
        titleField = new JTextField(20);
        controlPanel.add(titleField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        controlPanel.add(new JLabel("描述:"), gbc);

        gbc.gridx = 1;
        descriptionField = new JTextField(20);
        controlPanel.add(descriptionField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        controlPanel.add(new JLabel("优先级:"), gbc);

        gbc.gridx = 1;
        priorityComboBox = new JComboBox<>(new String[]{"低", "中", "高"});
        controlPanel.add(priorityComboBox, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        addButton = new JButton("添加任务");
        updateButton = new JButton("更新任务");
        deleteButton = new JButton("删除任务");

        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        controlPanel.add(buttonPanel, gbc);

        mainPanel.add(controlPanel, BorderLayout.EAST);

        // 添加事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addTask();
            }
        });

        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTask();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteTask();
            }
        });

        taskList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                Task selectedTask = taskList.getSelectedValue();
                if (selectedTask != null) {
                    titleField.setText(selectedTask.getTitle());
                    descriptionField.setText(selectedTask.getDescription());
                    priorityComboBox.setSelectedItem(selectedTask.getPriority());
                }
            }
        });

        add(mainPanel);
    }

    private void connectToDatabase() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            System.out.println("数据库连接成功");
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库连接失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void loadTasks() {
        listModel.clear();
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM tasks")) {

            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                String description = rs.getString("description");
                String priority = rs.getString("priority");
                boolean completed = rs.getBoolean("completed");
                Timestamp createdAt = rs.getTimestamp("created_at");

                listModel.addElement(new Task(id, title, description, priority, completed, createdAt));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载任务失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addTask() {
        String title = titleField.getText().trim();
        String description = descriptionField.getText().trim();
        String priority = (String) priorityComboBox.getSelectedItem();

        if (title.isEmpty()) {
            JOptionPane.showMessageDialog(this, "任务标题不能为空", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String sql = "INSERT INTO tasks (title, description, priority, completed, created_at) VALUES (?, ?, ?, ?, NOW())";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, title);
            pstmt.setString(2, description);
            pstmt.setString(3, priority);
            pstmt.setBoolean(4, false);

            pstmt.executeUpdate();
            loadTasks();
            clearFields();

            JOptionPane.showMessageDialog(this, "任务添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "添加任务失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateTask() {
        Task selectedTask = taskList.getSelectedValue();
        if (selectedTask == null) {
            JOptionPane.showMessageDialog(this, "请先选择一个任务", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String title = titleField.getText().trim();
        String description = descriptionField.getText().trim();
        String priority = (String) priorityComboBox.getSelectedItem();

        if (title.isEmpty()) {
            JOptionPane.showMessageDialog(this, "任务标题不能为空", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String sql = "UPDATE tasks SET title = ?, description = ?, priority = ?, completed = ? WHERE id = ?";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, title);
            pstmt.setString(2, description);
            pstmt.setString(3, priority);
            pstmt.setBoolean(4, selectedTask.isCompleted());
            pstmt.setInt(5, selectedTask.getId());

            pstmt.executeUpdate();
            loadTasks();
            clearFields();

            JOptionPane.showMessageDialog(this, "任务更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "更新任务失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteTask() {
        Task selectedTask = taskList.getSelectedValue();
        if (selectedTask == null) {
            JOptionPane.showMessageDialog(this, "请先选择一个任务", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除这个任务吗?", "确认", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            String sql = "DELETE FROM tasks WHERE id = ?";

            try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
                 PreparedStatement pstmt = conn.prepareStatement(sql)) {

                pstmt.setInt(1, selectedTask.getId());
                pstmt.executeUpdate();
                loadTasks();
                clearFields();

                JOptionPane.showMessageDialog(this, "任务删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (SQLException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "删除任务失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void clearFields() {
        titleField.setText("");
        descriptionField.setText("");
        priorityComboBox.setSelectedIndex(0);
        taskList.clearSelection();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TaskTrackerApp().setVisible(true);
            }
        });
    }

    private static class Task {
        private int id;
        private String title;
        private String description;
        private String priority;
        private boolean completed;
        private Timestamp createdAt;

        public Task(int id, String title, String description, String priority, boolean completed, Timestamp createdAt) {
            this.id = id;
            this.title = title;
            this.description = description;
            this.priority = priority;
            this.completed = completed;
            this.createdAt = createdAt;
        }

        public int getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }

        public String getDescription() {
            return description;
        }

        public String getPriority() {
            return priority;
        }

        public boolean isCompleted() {
            return completed;
        }

        public void setCompleted(boolean completed) {
            this.completed = completed;
        }

        public Timestamp getCreatedAt() {
            return createdAt;
        }

        @Override
        public String toString() {
            return title;
        }
    }

    private static class TaskListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            Task task = (Task) value;
            setText(task.getTitle() + " (" + task.getPriority() + ")");

            Color foreground = isSelected ? list.getSelectionForeground() : list.getForeground();
            Color background = isSelected ? list.getSelectionBackground() : list.getBackground();

            if (task.isCompleted()) {
                setForeground(Color.GRAY);
                setFont(getFont().deriveFont(Font.ITALIC));
            } else {
                setForeground(foreground);
                setFont(getFont().deriveFont(Font.PLAIN));
            }

            setBackground(background);
            return this;
        }
    }
}    